package com.SouthernWall_404.AgeDust.Common.Network.C2S;

import com.SouthernWall_404.AgeDust.Common.API.Capability.PlayerPersonality;
import com.SouthernWall_404.AgeDust.Common.API.Capability.PlayerPersonalityProvider;
import com.SouthernWall_404.AgeDust.Common.API.Info.AttributesInfo;
import com.SouthernWall_404.AgeDust.Common.API.Info.CharacterInfo;
import com.SouthernWall_404.AgeDust.Common.API.Util.NBTHandler;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class CharacterScreenClientPacket {

    public CharacterInfo characterInfo;
    public AttributesInfo attributesInfo;
    public CompoundTag modPack=new CompoundTag();
    public CharacterScreenClientPacket(CharacterInfo characterInfo,AttributesInfo attributesInfo)
    {
        modPack= NBTHandler.createModPack(characterInfo,attributesInfo);

    }
    public CharacterScreenClientPacket(FriendlyByteBuf buf)
    {
        this.modPack=buf.readNbt();
        this.characterInfo=NBTHandler.loadCharacterFromModPack(this.modPack);
        this.attributesInfo=NBTHandler.loadAttributeFromModPack(this.modPack);

    }

    public void encode(FriendlyByteBuf buf)
    {
        buf.writeNbt(this.modPack);

    }
    public boolean handle(Supplier<NetworkEvent.Context> ctx)
    {
//        ctx.get().enqueueWork(() ->
//                // 确保其仅在物理客户端上执行
//                DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> CharacterClientHandler.handleOpenPacket(this,ctx))
//        );
//        ctx.get().setPacketHandled(true);


        var content=ctx.get();
        content.enqueueWork(() -> {

            if(content.getSender().getCapability(PlayerPersonalityProvider.PLAYER_PERSONALITY_CAPABILITY).isPresent())
            {
                PlayerPersonality playerPersonality1=content.getSender().getCapability(PlayerPersonalityProvider.PLAYER_PERSONALITY_CAPABILITY).orElse(null);
                playerPersonality1.characterInfo=this.characterInfo;
                playerPersonality1.attributesInfo=this.attributesInfo;

//                content.getSender().setCustomName(Component.translatable(this.characterInfo.name));
//                content.getSender().setCustomNameVisible(true);
//                content.getSender().refreshDisplayName();

            }


        });
        content.setPacketHandled(true);
        return true;
    }
}
